package fischl;

import fischl.douyuApi.model.Danmu;
import fischl.model.DanmuGroup;

import java.util.*;

public final class DanmuUtil {

  // 去除同一用户在指定时间窗口内发送的重复内容弹幕
  public static int removeDuplicatedDanmus(List<Danmu> list, int windowSize) {
    final int originalCount = list.size();
    int baseTime = list.get(0).tl / 1000 + windowSize;
    Set<Danmu> window = new LinkedHashSet<>();
    ListIterator<Danmu> i = list.listIterator();
    Danmu danmu = null;

    while (danmu != null || i.hasNext()) {
      Danmu d = danmu != null ? danmu : i.next();
      danmu = null;
      if (d.tl / 1000 <= baseTime) {
        if (!window.add(d)) {
          i.remove();
        }
      } else {
        int timeToRemove = d.tl / 1000 - 10;
        window.removeIf(next -> next.tl / 1000 < timeToRemove);
        danmu = d;
        baseTime = d.tl / 1000;
      }
    }
    return originalCount - list.size();
  }

  public static List<DanmuGroup> findTopMinuteGroups(List<Danmu> list, int topCount) {
    Map<Integer, DanmuGroup> map = new LinkedHashMap<>();
    for (Danmu danmu : list) {
      int min = danmu.tl / 60 / 1000;
      DanmuGroup group = map.get(min);
      if (group == null) {
        group = new DanmuGroup();
        group.videoTime = min + "分钟";
        map.put(min, group);
      }
      group.list.add(danmu.toString());
    }
    ArrayList<DanmuGroup> danmuGroups = new ArrayList<>(map.values());
    danmuGroups.sort(new Comparator<DanmuGroup>() {
      @Override
      public int compare(DanmuGroup o1, DanmuGroup o2) {
        return o2.list.size() - o1.list.size(); // 从大到小
      }
    });
    danmuGroups.forEach(danmuGroup -> danmuGroup.danmuCount = danmuGroup.list.size());
    return danmuGroups.subList(0, Math.min(danmuGroups.size(), topCount));
  }
}
